package com.example.safeassistan.train.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.train.adapter.TestAmswerCardAdapter;
import com.example.safeassistan.train.model.PaperResultModel;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.WarningDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

/***
 * 答题卡
 * **/

public class ActivityTestAnswerCard extends BaseActivity implements View.OnClickListener {
    private TextView tvSubmit,tvMutil,tvJudge;
    private RecyclerView rcMuti,rcSignal,rcJduge;
    private TestAmswerCardAdapter singleAdapter;
    private TestAmswerCardAdapter multAdapter;
    private TestAmswerCardAdapter judgtAdapter;
    private List<List<String>>options;
    private String paperId="";

    public static void actionStart(Context context, List<List<String>> options,String paperId) {
        Intent intent = new Intent(context, ActivityTestAnswerCard.class);
        intent.putExtra("options",(Serializable) options);
        intent.putExtra("paperId",paperId);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_test_answer_card;
    }

    @Override
    protected void initView() {
        setTitleText("答题卡");
        options=(List<List<String>>) getIntent().getSerializableExtra("options");
        paperId=getIntent().getStringExtra("paperId");
        rcJduge=findViewById(R.id.rcJduge);
        rcMuti=findViewById(R.id.rcMuti);
        tvJudge=findViewById(R.id.tvJudge);
        tvMutil=findViewById(R.id.tvMutil);
        rcSignal=findViewById(R.id.rcSignal);
        tvSubmit=findViewById(R.id.tvSubmit);
        tvSubmit.setOnClickListener(this::onClick);
        for (int i=0;i<options.size();i++){
            for (int j=0;j<options.get(i).size();j++){
                if (options.get(i).get(j)==null||options.get(i).get(j).equals("")){
                    options.get(i).set(j,"X");
                }
            }
        }

        singleAdapter=new TestAmswerCardAdapter(options.get(0));
        rcSignal.setLayoutManager(new GridLayoutManager(getContext(),5));
        rcSignal.setAdapter(singleAdapter);

        if (options.get(1).size()>0){
            multAdapter=new TestAmswerCardAdapter(options.get(1));
            rcMuti.setLayoutManager(new GridLayoutManager(getContext(),5));
            rcMuti.setAdapter(multAdapter);
            tvMutil.setVisibility(View.VISIBLE);
        }else {
            tvMutil.setVisibility(View.GONE);
        }

        if (options.get(2).size()>0){
            tvJudge.setVisibility(View.VISIBLE);
            judgtAdapter=new TestAmswerCardAdapter(options.get(2));
            rcJduge.setLayoutManager(new GridLayoutManager(getContext(),5));
            rcJduge.setAdapter(judgtAdapter);
        }else {
            tvJudge.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvSubmit:
               for (int i=0;i<options.size();i++){
                   for (int j=0;j<options.get(i).size();j++){
                       if (options.get(i).get(j)==null||options.get(i).get(j).equals("")){
                           WarningDialog dialog=new WarningDialog(getContext(),"你还有题目未做完，确定交卷吗？",
                                   "取消","确定","");
                           dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                               @Override
                               public void doCancel() {
                                   dialog.dismiss();
                               }

                               @Override
                               public void doConfirm() {
                                   dialog.dismiss();
                                   computePaper();
                               }
                           });
                           dialog.show();
                           return;
                       }else {
                           computePaper();
                       }
                   }
               }
                break;
        }
    }

    public void computePaper(){
        //提交答题结果
        StringBuilder str=new StringBuilder();
        for (int p=0;p<options.size();p++){
            if (options.get(p).size()>0){
                for (int q=0;q<options.get(p).size();q++){
                    if (q==options.get(p).size()-1) {
                        str.append(options.get(p).get(q));
                    }else {
                        str.append(options.get(p).get(q)+",");
                    }

                }
                str.append(";");
            }else {
                str.append("X;");
            }
        }
        submitData(str.toString());
    }

    //提交答题卡
    public void submitData(String strs){
        JSONObject object=new JSONObject();
        try {
            object.put("answerStr",strs);
            object.put("id",paperId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(this).doPost(UrlConstants.submitAnswer, null,object, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        Object obj = JsonUtils.fromJson(result.toString(), PaperResultModel.class);
                        if (obj instanceof PaperResultModel) {
                            PaperResultModel model=(PaperResultModel) obj;
                            ActivityTrainResult.actionStart(getContext(),2,paperId,model);
                            finish();
                        }
                    }else {
                        Toast.makeText(ActivityTestAnswerCard.this,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
